package com.nineclock.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;

/**
 * 授权服务配置
 */

/**
 * 授权码模式改为密码授权
 */
@Configuration
@EnableAuthorizationServer //开启oauth2.0授权服务
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    DataSource dataSource;

    @Bean
    public ClientDetailsService clientDetailsService(){
        return new JdbcClientDetailsService(dataSource);
    }

    //配置客户端的详情信息
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /*clients.inMemory()
                //所有信息全部正确才能访问, 这些数据的会保存的数据库中
                //配置客户端的标识
                .withClient("nc_client_app")                      //APP端
                .secret(passwordEncoder.encode("123456"))     //密钥
                .scopes("all")
                .redirectUris("http://localhost")                         //重定向的路径
                .authorizedGrantTypes("authorization_code", "password")
                .and()
                .withClient("nc_client_pc")                       //PC端
                .secret(passwordEncoder.encode("123456"))
                .scopes("all")
                .redirectUris("http://localhost")
                .authorizedGrantTypes("authorization_code", "password");*/

        clients.withClientDetails(clientDetailsService());
    }

    /**
     * 令牌端点安全约束
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll") //tokenkey当使用JwtToken且使用非对称加密时，资源服务用于获取公钥而开放的，这里指这个 endpoint(/oauth/token )完全公开
                .checkTokenAccess("permitAll") //checkToken这个endpoint(/oauth/authorize) 完全公开
                .allowFormAuthenticationForClients(); //允许表单认证(密码/授权码模式认证)
    }

    
    @Autowired
    AuthenticationManager authenticationManager;
    
    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    TokenStore tokenStore;
    
    @Autowired
    JwtAccessTokenConverter tokenConverter;
    
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        //token的客户端详情信息
        tokenServices.setClientDetailsService(clientDetailsService);
        //token的存储对象
        tokenServices.setTokenStore(tokenStore);
        //刷新令牌时间支持
        tokenServices.setSupportRefreshToken(true);
        //token的有效期,秒
        tokenServices.setAccessTokenValiditySeconds(60*60*12);
        //token刷新令牌的有效时间,秒
        tokenServices.setRefreshTokenValiditySeconds(60*60*24*30);
        //配置token增强
        tokenServices.setTokenEnhancer(tokenConverter);

        return tokenServices;

    }
    
    

    /**
     * 令牌访问端点配置
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenServices(tokenServices())
                .authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }
}